package xml;

import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import dataStructures.*;

import javax.xml.stream.*;
import javax.xml.stream.events.*;


@SuppressWarnings("restriction")
public class QueryWriter extends XMLWriter {
	
	public QueryWriter(String filenameTimeStamp) {
		super(filenameTimeStamp);
	}


	public void writeQuery(MyQuery query) {
		try {
			// Create a XMLOutputFactory
			XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
			// Create XMLEventWriter
			XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(
					new FileOutputStream("data" + System.getProperty("file.separator") + filenameTimeStamp), "UTF-8");
			// Create a EventFactory
			XMLEventFactory eventFactory = XMLEventFactory.newInstance();
			XMLEvent end = eventFactory.createDTD("\n");
			// Create and write Start Tag
			StartDocument startDocument = eventFactory.createStartDocument();
			eventWriter.add(startDocument);
			//simply add a new line
			eventWriter.add(eventFactory.createCharacters("\n"));
	
			// Create config open tag
			StartElement configStartElement = eventFactory.createStartElement("","", Const.QUERY);
			eventWriter.add(configStartElement);
			
			//simply adding an attribute
			Attribute attribute = eventFactory.createAttribute("term", query.term);
			eventWriter.add(attribute);
			eventWriter.add(end);
			
			Map<String, String> attributes = new HashMap<String, String>();
			attributes.put(Const.LATITUDE, query.location.latitude);
			attributes.put(Const.LONGITUDE, query.location.longitude);
			attributes.put(Const.RADIUS, query.location.radius);
			attributes.put(Const.UNIT, query.location.unit);
			createNode(eventWriter, "location", "", attributes);
	
			eventWriter.add(eventFactory.createEndElement("", "", Const.QUERY));
			eventWriter.add(end);
			eventWriter.add(eventFactory.createEndDocument());
			eventWriter.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
